import Big from 'big.js'
export function ExportExcel(tableData, name, headerData, time, searchForm, pageData, totalWord) { // table为表格数据,name为导出文件名,headerData为表头名，//callback为导出完毕回调,方便你知道导出完成了(可根据自己需求决定是否需要)
  const times = searchForm.filter(item => item.type == 'time' && item.isTime)
  console.log(times)
  const timeData = JSON.parse(JSON.stringify(times))
  times.forEach(item => {
    if (!pageData[item.prop]) {
      timeData.splice(timeData.indexOf(item), 1)
    }
  })
  const time1 = timeData.length > 0 ? timeData[0].label + ':' + '\xa0' + pageData[timeData[0].prop][0].substring(0, 10) + '\xa0' + '00:00' + '\xa0' + '至' + '\xa0' + pageData[timeData[0].prop][1].substring(0, 10) + '\xa0' + '00:00' : ''
  const time2 = timeData.length > 1 ? timeData[1].label + ':' + '\xa0' + pageData[timeData[1].prop][0].substring(0, 10) + '\xa0' + '00:00' + '至' + '\xa0' + pageData[timeData[1].prop][1].substring(0, 10) + '\xa0' + '00:00' : ''
  const time3 = timeData.length > 2 ? timeData[2].label + ':' + '\xa0' + pageData[timeData[2].prop][0].substring(0, 10) + '\xa0' + '00:00' + '至' + '\xa0' + pageData[timeData[2].prop][1].substring(0, 10) + '\xa0' + '00:00' : ''
  let tableInnerHTML = ''
  var bodyData = tableData // 这里对应是表格数据，我们只需要传过来即可
  tableInnerHTML += '<table>'
  tableInnerHTML += '<thead>'
  tableInnerHTML += '<tr>'
  tableInnerHTML += `<td align='center' colspan=${headerData.map(item => item.label).length}
  style='border-right:0.5px solid #666;font-size:24px;height:50px'>` +
  name +
  '</td>'
  tableInnerHTML += '</tr>' // 头部部分结束
  tableInnerHTML += '<tr>' // 头部部分开始拼接！
  tableInnerHTML += `<th colspan=${headerData.map(item => item.label).length}
    				style='border:0.5px solid #666;height:40px;''>` + '\xa0\xa0\xa0\xa0\xa0\xa0' + time1 + '\xa0\xa0\xa0\xa0\xa0\xa0' + time2 + '\xa0\xa0\xa0\xa0\xa0\xa0' + time3 + '\xa0\xa0\xa0\xa0\xa0\xa0' + '导出日期:' + '\xa0' + time

  '</th></tr>'
  tableInnerHTML += '<tr>'
  headerData.map(item => item.label).forEach(item => {
    tableInnerHTML += "<th rowspan='1' style='border:0.5px solid #666;height:30px;'>" +
            item + '</th>'
  })
  tableInnerHTML += '</tr></thead>' // 头部部分结束
  tableInnerHTML += '<tbody>' // 身体部分开始
  if (bodyData && bodyData.length > 0) {
    bodyData.forEach(item => {
      tableInnerHTML += '<tr>'
      headerData.forEach(ele => {
        if (ele.position == 'right') {
          tableInnerHTML += "<td x:str align='right' style='border:0.5px solid #666;height:30px;'>" + (item[ele.prop] == null ? '' : item[ele.prop]) + '</td>'
        } else if (ele.position == 'left') {
          tableInnerHTML += "<td x:str align='left' style='border:0.5px solid #666;height:30px;'>" + (item[ele.prop] == null ? '' : item[ele.prop]) + '</td>'
        } else {
          tableInnerHTML += "<td x:str align='center' style='border:0.5px solid #666;height:30px;'>" + (item[ele.prop] == null ? '' : item[ele.prop]) + '</td>'
        }
      })
      tableInnerHTML += '</tr>'
    })
  }

  if (totalWord && totalWord.length > 0) {
    console.log(11111)
    //  合计
    tableInnerHTML += '<tr>'
    headerData.forEach((ele, index) => {
      if (totalWord.indexOf(ele.prop) != -1) {
        if (ele.position == 'right') {
          tableInnerHTML += "<td x:str align='right' style='border:0.5px solid #666;height:30px;'>" + (sum(bodyData.map(item2 => item2[ele.prop]))) + '</td>'
        } else if (ele.position == 'left') {
          tableInnerHTML += "<td x:str align='left' style='border:0.5px solid #666;height:30px;'>" + (sum(bodyData.map(item2 => item2[ele.prop]))) + '</td>'
        } else {
          tableInnerHTML += "<td x:str align='center' style='border:0.5px solid #666;height:30px;'>" + (sum(bodyData.map(item2 => item2[ele.prop]))) + '</td>'
        }
      } else if (index == 0 && totalWord.indexOf(ele.prop) == -1) {
        tableInnerHTML += "<td x:str align='center' style='border:0.5px solid #666;height:30px;'>" + '合计' + '</td>'
      } else {
        tableInnerHTML += "<td x:str align='center' style='border:0.5px solid #666;height:30px;'>" + '' + '</td>'
      }
    })
    tableInnerHTML += '</tr>'
  }
  tableInnerHTML += '</tbody>' // 身体结束
  tableInnerHTML += '</table>' // 身体结束
  // ------------OK，到此为止拼接工作做完，也就是基本的数据已经被拼接成表格了--------------------
  // tip开始(下面还有个tip结束的位置)
  /* -------从tip开始到tip结束的过程是判断浏览器类型步骤，做兼容性处理！对于你来说你完全可以不用
             深入理解这里面的逻辑，直接复制到自己的项目里去，不会存在任何浏览器兼容性的问题！*/
  function getExplorer() {
    var explorer = window.navigator.userAgent
    if (explorer.indexOf('MSIE') >= 0) {
      return 'ie' // ie
    } else if (explorer.indexOf('Firefox') >= 0) {
      return 'Firefox' // firefox
    } else if (explorer.indexOf('Chrome') >= 0) {
      return 'Chrome' // Chrome
    } else if (explorer.indexOf('Opera') >= 0) {
      return 'Opera' // Opera
    } else if (explorer.indexOf('Safari') >= 0) {
      return 'Safari' // Safari
    }
  }

  if (getExplorer() !== 'Safari' && name.substr(-1, 4) !== '.xls') {
    name += '.xls'
  }
  return tableInnerHTML
  //   if (getExplorer() === 'ie') {
  //     var curTbl = table
  //     var oXL = new ActiveXObject('Excel.Application')
  //     var oWB = oXL.Workbooks.Add()
  //     var xlsheet = oWB.Worksheets(1)
  //     var sel = document.body.createTextRange()
  //     sel.moveToElementText(curTbl)
  //     sel.select()
  //     sel.execCommand('Copy')
  //     xlsheet.Paste()
  //     oXL.Visible = true
  //     try {
  //       var fname = oXL.Application.GetSaveAsFilename('Excel.xls', 'Excel Spreadsheets (*.xls), *.xls')
  //     } catch (e) {
  //       print('Nested catch caught ' + e)
  //     } finally {
  //       oWB.SaveAs(fname)
  //       // oWB.Close(savechanges = false);
  //       oXL.Quit()
  //       oXL = null
  //       idTmr = setInterval(Cleanup(), 1)
  //     }
  //   } else {
  // tip结束
} // 此括号结束，我们自己封装的exportExcel方法也结束了！90%的逻辑完成了！
/* 下面的两个函数对于你来说你也完全不用深入理解里面的逻辑，你只要知道，他是在帮助你做转换，帮助你
  将拼接好的HTML字符串模板真正地转换并且输出到Excel里面去，直接当成固定书写方法，直接拿来用即可*/
// function Cleanup() {
//   window.clearInterval(idTmr)
// }
// 求和
function sum(arr) {
  var sum = 0
  for (var i = 0; i < arr.length; i++) {
    // if (arr[i].indexOf(',') != -1) {
    //   arr[i] = arr[i].replace(/,|，/g, '')
    // }

    sum = new Big(sum).plus(Number(arr[i])).toString()
  }
  return sum
}
// const tableToExcel = (function() {
//   const template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>'
//   const format = function(s, c) {
//     return s.replace(/{(\w+)}/g, function(m, p) { return c[p] })
//   }
//   return function(table, name) {
//     const ctx = { worksheet: name || 'Worksheet', table: table }
//     const blob = new Blob([format(template, ctx)])
//     const a = document.createElement('a')
//     a.href = URL.createObjectURL(blob)
//     a.download = name // 这里这个name就是对应的文件名！
//     a.click()
//     a.remove()
//     // callback('success') /* 这里调用我们自己传入的回调方法，这样导出Excel完成后你就能在外面知道导出完毕，并且再往下做自己其他的逻辑*/
//   }
// })()
function tablesToExcel(contents, fileName) {
  const uri = 'data:application/vnd.ms-excel;base64,'
  const html_start = `<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>`
  const template_ExcelWorksheet = `<x:ExcelWorksheet><x:Name>{SheetName}</x:Name><x:WorksheetSource HRef="sheet{SheetIndex}.htm"/><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>`
  const template_ListWorksheet = `<o:File HRef="sheet{SheetIndex}.htm"/>`
  const template_HTMLWorksheet = `
------=_NextPart_dummy
Content-Location: sheet{SheetIndex}.htm
Content-Type: text/html; charset=windows-1252

` + html_start + `
<head>
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<link id="Main-File" rel="Main-File" href="../WorkBook.htm">
<link rel="File-List" href="filelist.xml">
</head>
<body>{SheetContent}</body>
</html>`
  const template_WorkBook = `MIME-Version: 1.0
X-Document-Type: Workbook
Content-Type: multipart/related; boundary="----=_NextPart_dummy"

------=_NextPart_dummy
Content-Location: WorkBook.htm
Content-Type: text/html; charset=windows-1252

` + html_start + `
<head>
<meta name="Excel Workbook Frameset">
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<link rel="File-List" href="filelist.xml">
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>{ExcelWorksheets}</x:ExcelWorksheets>
<x:ActiveSheet>0</x:ActiveSheet>
</x:ExcelWorkbook>
</xml><![endif]-->
</head>
<frameset>
<frame src="sheet0.htm" name="frSheet">
<noframes><body><p>This page uses frames, but your browser does not support them.</p></body></noframes>
</frameset>
</html>
{HTMLWorksheets}
Content-Location: filelist.xml
Content-Type: text/xml; charset="utf-8"

<xml xmlns:o="urn:schemas-microsoft-com:office:office">
<o:MainFile HRef="../WorkBook.htm"/>
{ListWorksheets}
<o:File HRef="filelist.xml"/>
</xml>
------=_NextPart_dummy--
`
  const base64 = (s) => {
    return window.btoa(unescape(encodeURIComponent(s)))
  }
  const format = (s, c) => {
    return s.replace(/{(\w+)}/g, function(m, p) {
      return c[p]
    })
  }
  const context_WorkBook = {
    ExcelWorksheets: '',
    HTMLWorksheets: '',
    ListWorksheets: ''
  }
  contents.forEach((p, SheetIndex) => {
    const SheetName = p.sheetName || 'Sheet' + SheetIndex
    context_WorkBook.ExcelWorksheets += format(template_ExcelWorksheet, {
      SheetIndex: SheetIndex,
      SheetName: SheetName
    })
    let content = p.content
    if (p.tableId) {
      content = document.getElementById(p.tableId).outerHTML
    }
    context_WorkBook.HTMLWorksheets += format(template_HTMLWorksheet, {
      SheetIndex: SheetIndex,
      SheetContent: content
    })
    context_WorkBook.ListWorksheets += format(template_ListWorksheet, {
      SheetIndex: SheetIndex
    })
  })
  const link = document.createElement('A')
  link.href = uri + base64(format(template_WorkBook, context_WorkBook))
  link.download = fileName || 'Workbook.xls'
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
export function downloadExcel(template, name) {
  // var arr = []
  // template.forEach(ele => {
  //   arr.push({ content: '<table>' + ele.template + '</table>', sheetName: ele.sheetName })
  // })
  // const htmlValue = template
  // const htmlValue1 = `<table border="1px" style="border-spacing:0;text-align:center"><thead><tr><th colspan="11">造价指标</th></tr><tr><th>序号</th><th>项目名称</th><th colspan="4">桥梁名称</th><th>设计数量1231</th><th>设计数量2123123</th><th>造价指标1123123</th><th>造价指标2</th><th>金额123123</th></tr></thead><tbody><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9=11/7</td><td>10=11/8</td><td>11</td></tr><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9=11/7</td><td>10=11/8</td><td>11</td></tr></tbody></table>`

  tablesToExcel(template, name)
  return
}
// export default ExportExcel // 导出自己封装的exportExcel方法
